var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
let cors = require("cors");

var app = express();
app.use(cors());

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use(logger("dev"));

// 解析请求体中json数据
app.use(express.json());
// 解析请求体中www-form数据
app.use(express.urlencoded({ extended: false }));
//中间件 解析请求体中 formData数据

app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// // 解析 jwt
var { expressjwt } = require("express-jwt");
app.use(
  expressjwt({
    // 解析的 传入 刚刚加密的密码 --加密算法
    secret: "test123",
    algorithms: ["HS256"],
  }).unless({
    // 排除 不需要 验证token的接口
    path: [
      /^\/todos/,
      {
        url: /^\/articles/,
        methods: ["GET"],
      },
      {
        url: /^\/users/,
        methods: ["GET", "POST"],
      },
      // "/api/users",
      // // "/api/articles/users/:uid", 这样的路由，必须使用正则匹配
      // /^\/api\/articles\/users\/\w+/,
      // {
      //   url: /^\/api\/articles\/\w+/,
      //   methods: ["GET"],
      // },
    ],
  })
);

app.use(function (err, req, res, next) {
  console.log(err);
  if (err.status === 401) {
    res.status(401).json({ code: 0, msg: err.code });
  } else {
    next(err);
  }
});

// app.use(function (req, res) {
//   // // 获取 token  解析 token --
// });

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var todosRouter = require("./routes/todos");
var articlesRouter = require("./routes/articles");
var uploadRouter = require("./routes/upload");
const { log } = require("console");
app.use("/", indexRouter);
// 商店 管理员的 注册--登录
app.use("/shop/users", usersRouter);
app.use("/todos", todosRouter);
// 商店商品的，发布 删除 修改 列表
app.use("/shop/articles", articlesRouter);
// 上传图片接口
app.use("/upload-img", uploadRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
